package com.jhd.fuzhou.view.task;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.jhd.fuzhou.view.login.BaseActivity;
import com.jhd.fuzhou.view.login.FuzhouApplication;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.service.ProcessService;
import com.jhd.fuzhou.service.TaskService;
import com.jhd.fuzhou.util.CustomToast;
import com.jhd.fuzhou.util.UtilHelper;
import com.jhd.fuzhou.view.daily.DailyStepOneActivity;
import com.jhd.fuzhou.view.random.DoubleStepOneActivity;
import com.jhd.fuzhou.view.special.SpecialStepOneActivity;
import com.jhd.fuzhou.vo.JsonForResult;
import com.jhd.fuzhou.vo.PersonInfoVo;
import com.jhd.fuzhou.vo.SupervisionInspectionVo;

import net.zigin.commons.util.ParamsMapUtil;
import net.zigin.commons.util.StringUtil;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import static com.jhd.fuzhou.util.StartProcess.completeByAssign2;
import static com.jhd.fuzhou.util.StartProcess.getProInstanceId;

/*任务详情
* 科长未通过。为驳回
* 专管领导驳回，为未通过*/
public class TaskDetailActivity extends BaseActivity {
    private SupervisionInspectionVo supervisionInspectionVo,supervisionInspectionVoDetail;
    private String data;
    private Context context=this;
    @BindView(R.id.lin_status)LinearLayout lin_status;//顶部状态，根据值来进行隐藏和修改
    @BindView(R.id.linearLayoutBottom)LinearLayout linearLayoutBottom;//顶部状态，根据值来进行隐藏和修改
    @BindView(R.id.rel_random_check)RelativeLayout rel_random_check;//抽查项目
    @BindView(R.id.tv_process_status)TextView tv_process_status;//进程状态
    @BindView(R.id.tv_process_reason)TextView tv_process_reason;//驳回理由
    @BindView(R.id.tv_process_person)TextView tv_process_person;//驳回人员
    @BindView(R.id.tv_process_date)TextView tv_process_date;//审核日期
    @BindView(R.id.tv_unitName)TextView tv_unitName;//被监督单位
    @BindView(R.id.tv_status)TextView tv_status;//经营状态
    @BindView(R.id.tv_creditCode)TextView tv_creditCode;//社会信用代码
    @BindView(R.id.tv_superviseSector)TextView tv_superviseSector;//监管机构
    @BindView(R.id.tv_superviseOffice)TextView tv_superviseOffice;//监管部门
    @BindView(R.id.tv_date)TextView tv_date;//检查日期
    @BindView(R.id.tv_task_type)TextView tv_task_type;//检查类型
    @BindView(R.id.tv_inspectResult)TextView tv_inspectResult;//检查结果
    @BindView(R.id.tv_speciality)TextView tv_speciality;//所属专业
    @BindView(R.id.tv_specialityDetail)TextView tv_specialityDetail;//专业明细
    @BindView(R.id.btn_post)Button btn_post;//提交
    @BindView(R.id.btn_update)Button btn_update;//更新
    private List<Process> processList;
    private List<PersonInfoVo> personInfoVos;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_task_detail);
    }

    @Override
    protected void processLogic() {
        application.addTaskActivity(this);
        onBack();
        data=getIntent().getStringExtra("data");
        String isFinish = getIntent().getStringExtra("isFinish");
        if(isFinish.equals("1")){
            linearLayoutBottom.setVisibility(View.GONE);
        }
        supervisionInspectionVo=JSON.parseObject(data, SupervisionInspectionVo.class);
        String approvalStatus=supervisionInspectionVo.getApprovalStatus();
        String progress=supervisionInspectionVo.getProgress();
        if("报告".equals(progress)){
            btn_update.setText("修改");
        }else{
            btn_update.setText("查看");
            supervisionInspectionVo.setIsOnlyLook("1");
        }
        if("未审核".equals(approvalStatus)){
            if("报告".equals(progress)){
                btn_post.setText("提交");
                btn_update.setVisibility(View.VISIBLE);
            }else if("科长审核".equals(progress)){
                btn_post.setText("审核任务");
            }else if("分管领导审核".equals(progress)){
                btn_post.setText("重新提交");lin_status.setVisibility(View.VISIBLE);
            }
        }else if("已审核".equals(approvalStatus)){//其实只存在分管领导审核的状态
            btn_post.setText("撤销审核");
        }else if("已驳回".equals(approvalStatus)){//只存在报告状态
            btn_update.setVisibility(View.VISIBLE);
//            btn_post.setVisibility(View.GONE);//将提交按钮隐藏
//            btn_post.setText("修改");lin_status.setVisibility(View.VISIBLE);
            btn_post.setText("提交");lin_status.setVisibility(View.VISIBLE);
        }
        setData();
        if(btn_post.getText().toString().equals("审核任务")){
            getTaskApproveLeve2();
        }else{
            getTaskApproveLeve1();
        }
        getProInstanceId(application,supervisionInspectionVo.getId(),supervisionInspectionVo.getApprovalStatus(),tv_process_status,tv_process_reason,tv_process_person,tv_process_date,context);
        getSupervisionInspectionDetail(supervisionInspectionVo.getId(),supervisionInspectionVo.getSupervisedType());
    }
    public void setData(){
        tv_unitName.setText(supervisionInspectionVo.getUnitName());//被监督单位
        if ("0".equals(supervisionInspectionVo.getBusinessStatus())) {
            tv_status.setText("关闭");//经营状态
        } else if ("1".equals(supervisionInspectionVo.getBusinessStatus())) {
            tv_status.setText("正常");//经营状态
        }
        tv_creditCode.setText(supervisionInspectionVo.getCreditCode());//社会信用代码
        tv_superviseSector.setText(supervisionInspectionVo.getSuperviseSector());//监管机构
        tv_superviseOffice.setText(supervisionInspectionVo.getSuperviseOffice());//监管部门
        tv_date.setText(supervisionInspectionVo.getCreateTime().substring(0,11));//检查日期
        if("0".equals(supervisionInspectionVo.getSupervisedType())){
            tv_task_type.setText("日常监督");
            rel_random_check.setVisibility(View.GONE);
        }else if("1".equals(supervisionInspectionVo.getSupervisedType())){
            tv_task_type.setText("专项监督");
            rel_random_check.setVisibility(View.GONE);
        }else if("2".equals(supervisionInspectionVo.getSupervisedType())){
            tv_task_type.setText("国家双随机");
        }else if("3".equals(supervisionInspectionVo.getSupervisedType())){
            tv_task_type.setText("省级双随机");
        }
        if("1".equals(supervisionInspectionVo.getInspectResult())){
            tv_inspectResult.setText("合格");
            tv_inspectResult.setTextColor(getResources().getColor(R.color.green));
        }else{
            tv_inspectResult.setText("不合格");
            tv_inspectResult.setTextColor(getResources().getColor(R.color.red));
        }
        tv_speciality.setText(supervisionInspectionVo.getSpecialityCategory());//所属专业
        tv_specialityDetail.setText(supervisionInspectionVo.getSpecialityDetail());//专业明细
    }

    @OnClick({R.id.btn_post,R.id.btn_update,R.id.rel_document,R.id.rel_check_content,R.id.rel_law_enforcement_video,R.id.rel_random_check})
    public void onClick(View v){
        switch (v.getId()){
            case R.id.btn_update:
                if("0".equals(supervisionInspectionVo.getSupervisedType())){
                    application.addStepActivity(this);
                    Intent intent=new Intent(context, DailyStepOneActivity.class);
                    if("查看".equals(btn_update.getText().toString())){
                        intent.putExtra("isOnlyLook", supervisionInspectionVo.getIsOnlyLook());
                    }
                    intent.putExtra("id",supervisionInspectionVo.getId());
                    intent.putExtra("taskId",supervisionInspectionVo.getTaskId());
                    startActivity(intent);
                }else if("1".equals(supervisionInspectionVo.getSupervisedType())){
                    application.addStepActivity(this);
                    Intent intent=new Intent(context, SpecialStepOneActivity.class);
                    if("查看".equals(btn_update.getText().toString())){
                        intent.putExtra("isOnlyLook", supervisionInspectionVo.getIsOnlyLook());
                    }
                    intent.putExtra("id",supervisionInspectionVo.getId());
                    intent.putExtra("taskId",supervisionInspectionVo.getTaskId());
                    startActivity(intent);
                }else if("2".equals(supervisionInspectionVo.getSupervisedType())||"3".equals(supervisionInspectionVo.getSupervisedType())){//国家双随机,省级双随机
                    application.addStepActivity(this);
                    Intent intent=new Intent(context, DoubleStepOneActivity.class);
                    if("查看".equals(btn_update.getText().toString())){
                        intent.putExtra("isOnlyLook", supervisionInspectionVo.getIsOnlyLook());
                    }
                    intent.putExtra("specialityCategory",supervisionInspectionVo.getSpecialityCategory());
                    intent.putExtra("id",supervisionInspectionVo.getId());
                    intent.putExtra("taskId",supervisionInspectionVo.getTaskId());
                    startActivity(intent);
                }
                break;
            case R.id.btn_post:
                String approvalStatus=supervisionInspectionVo.getApprovalStatus();
                String progress=supervisionInspectionVo.getProgress();
                String status=btn_post.getText().toString();
                if(status.equals("提交")){
                    AlertDialog.Builder builder = new AlertDialog.Builder(context);
                    builder.setTitle("修改成功，是否提交审批?");
                    builder.setMessage("提交后不可再更改");
                    builder.setIcon(R.mipmap.dialog_alert);
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            completeByAssign2(application,personInfoVos.get(0).getUserName(),
                                    supervisionInspectionVo.getTaskId(),null,null,supervisionInspectionVo.getId(),"未审核","提交成功！",context);
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    Dialog dialog = builder.create();
                    if (!((Activity) context).isFinishing()) dialog.show();
                    int color = context.getResources().getColor(R.color.header);
                    Button btn = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
                    Button btn2 = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_NEGATIVE);
                    if (btn != null) btn.setTextColor(color);
                    if (btn2 != null) btn2.setTextColor(color);
                }else{//无需判断status为修改时，因为按钮隐藏了，需要修改才能提交
                    if("待审核".equals(approvalStatus)||"未审核".equals(approvalStatus)||"已驳回".equals(approvalStatus)){
                        Intent intent=new Intent(context, AuditTaskActivity.class);
                        Gson gson = new Gson();
                        intent.putExtra("data", gson.toJson(supervisionInspectionVo));
                        startActivityForResult(intent,1);
                    }else if("已审核".equals(approvalStatus)){//只存在报告状态
                        Intent intent=new Intent(context, CancelAuditActivity.class);
                        Gson gson = new Gson();
                        intent.putExtra("data", gson.toJson(supervisionInspectionVo));
                        startActivityForResult(intent,1);
                    }
                }
                break;
            case R.id.rel_document:
                if(supervisionInspectionVoDetail==null){
                    getSupervisionInspectionDetail(supervisionInspectionVo.getId(),supervisionInspectionVo.getSupervisedType());
                }else{
                    Intent intent=new Intent(context,DocumentActivity.class);
                    Gson gson = new Gson();
                    intent.putExtra("data", gson.toJson(supervisionInspectionVoDetail));
                    startActivity(intent);
                }
                break;
            case R.id.rel_check_content:
                if(supervisionInspectionVoDetail==null){
                    getSupervisionInspectionDetail(supervisionInspectionVo.getId(),supervisionInspectionVo.getSupervisedType());
                }else{
                    Intent intent=new Intent(context, InspectResultActivity.class);
                    Gson gson = new Gson();
                    intent.putExtra("data", gson.toJson(supervisionInspectionVoDetail));
                    startActivity(intent);
                }
                break;
            case R.id.rel_law_enforcement_video:
                if(supervisionInspectionVoDetail==null){
                    getSupervisionInspectionDetail(supervisionInspectionVo.getId(),supervisionInspectionVo.getSupervisedType());
                }else{
                    Intent intent=new Intent(context,LawEnforcementVideoActivity.class);
                    Gson gson = new Gson();
                    intent.putExtra("data", gson.toJson(supervisionInspectionVoDetail));
                    startActivity(intent);
                }
                break;
            case R.id.rel_random_check:
                if(supervisionInspectionVoDetail==null){
                    getSupervisionInspectionDetail(supervisionInspectionVo.getId(),supervisionInspectionVo.getSupervisedType());
                }else{
                    Intent intent=new Intent(context,RandomCheckActivity.class);
                    Gson gson = new Gson();
                    intent.putExtra("data", gson.toJson(supervisionInspectionVoDetail));
                    startActivity(intent);
                }
                break;
        }
    }
    public void getTaskApproveLeve1(){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        ProcessService vs = retrofit.create(ProcessService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("username",application.getName()).addParam("userId",application.getUserId());
        Call<JsonForResult> jsonForResultCall = vs.getTaskApproveLeve1(application.getAccessToken(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if(jsonForResult.getData()!=null){
                            personInfoVos= JSON.parseArray(jsonForResult.getData().toString(), PersonInfoVo.class);
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    public void getTaskApproveLeve2(){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        ProcessService vs = retrofit.create(ProcessService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("username",application.getName()).addParam("userId",application.getUserId());
        Call<JsonForResult> jsonForResultCall = vs.getTaskApproveLeve2(application.getAccessToken(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if(jsonForResult.getData()!=null){
                            personInfoVos= JSON.parseArray(jsonForResult.getData().toString(), PersonInfoVo.class);
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    public void getSupervisionInspectionDetail(String id, String supervisedType){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
//        Retrofit retrofit = UtilHelper.retrofit(application,"http://192.168.1.96:9004/");//URL的头
        TaskService vs = retrofit.create(TaskService.class);
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("id",id);
        params.put("supervisedType",supervisedType);
        Call<JsonForResult> jsonForResultCall = vs.getSupervisionInspectionDetail(application.getAccessToken(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            private SupervisionInspectionVo supervisionInspectionVoList;

            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if(jsonForResult.getData()!=null){
                            supervisionInspectionVoDetail= JSON.parseObject(jsonForResult.getData().toString(), SupervisionInspectionVo.class);
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode ==RESULT_OK) {
            if(data.getStringExtra("position").equals("1")){
                finish();
            }
        }
    }

}